package common

import (
	"fmt"
	"github.com/beego/beego/v2/server/web"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
)

//数据库连接对象已经在这里初始化了

var DB *gorm.DB

func init() {
	dbUser, _ := web.AppConfig.String("DBUserName")
	dbPassword, _ := web.AppConfig.String("DBPassword")
	dbHost, _ := web.AppConfig.String("DBHost")
	dbPort, _ := web.AppConfig.String("DBPort")
	dbName, _ := web.AppConfig.String("DBName")

	// 构建 DSN
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local",
		dbUser, dbPassword, dbHost, dbPort, dbName)

	// 连接数据库
	var err error
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatalf("failed to connect database: %v", err)
	} else {
		log.Println("successfully connected to MySQL")
	}
}
